import { requestUrl, version } from '../config';

export function request(url, method, data, tip) {
  if (tip == null || tip == "") {
    my.showLoading({ content: "加载中..." });
  } else {
    my.showLoading({ content: tip });
  }
  var promise = new Promise((resolve, reject, defaults) => {
    const userInfo = my.getStorageSync({key: 'userInfo'})
    // let shopId = my.getStorageSync({key:'shopId'}).data
    // if (!shopId) {
    //   shopId = my.getExtConfigSync().shopId;

    // }
    const accountInfo = my.getAccountInfoSync();
    my.request({
      url: requestUrl + url,
      headers: {
        // ShopId: shopId || '',
        appId: accountInfo.miniProgram.appId || '', 
        appVersion: version,
        Token: (userInfo.data && userInfo.data.token) ? userInfo.data.token : ''
      },
      method: method,
      data: data,
      timeout: 0,
      dataType: 'json',
      success: (result) => {
        my.hideLoading();
        // if (!shopId) {
        //   shopId = result.data.shopId;
        //   my.setStorageSync({key:'shopId',data:shopId})

        // }
        if (result.data.code == 403) {
          my.removeStorageSync({
            key:'userInfo'
          })
        }
        resolve(result.data);
      },
      fail: (err) => {
        console.log(err, 'ooooooooo')
        if (err.data.code == 403) {
          my.removeStorageSync({
            key:'userInfo'
          })
        }
        if(err.data.message) {
          my.showToast({content: err.data.message});

        }

        my.hideLoading();
        reject(err);
      },
      complete: () => {
        my.hideLoading();
        defaults;
      }
    });
  });
  return promise;
}